<template>
  <div>
    <!-- 发布头部 -->
    <div class="publish-header">
      <div class="container text-center">
        <h1 class="mb-3">发布实习/兼职信息</h1>
        <p class="mb-0">快速发布招聘信息，找到合适的校园人才</p>
      </div>
    </div>

    <div class="container publish-container">
      <!-- 步骤指示器 -->
      <div class="step-indicator">
        <div class="step" :class="{ active: currentStep === 1 }" data-step="1">
          <div class="step-number">1</div>
          <div class="step-label">基本信息</div>
        </div>
        <div class="step" :class="{ active: currentStep === 2 }" data-step="2">
          <div class="step-number">2</div>
          <div class="step-label">职位详情</div>
        </div>
        <div class="step" :class="{ active: currentStep === 3 }" data-step="3">
          <div class="step-number">3</div>
          <div class="step-label">联系方式</div>
        </div>
      </div>

      <form id="jobPublishForm" @submit.prevent="submitForm">
        <!-- 第一步：基本信息 -->
        <div class="form-section" :class="{ active: currentStep === 1 }" id="step1">
          <div class="publish-card">
            <h3 class="section-title">基本信息</h3>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="jobTitle" class="form-label required">职位名称</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="jobTitle" 
                  placeholder="例如：Java开发实习生" 
                  v-model="formData.jobTitle"
                  :class="{ 'is-invalid': errors.jobTitle }"
                  required
                >
                <div class="invalid-feedback" v-if="errors.jobTitle">{{ errors.jobTitle }}</div>
              </div>
              <div class="col-md-6 mb-3">
                <label for="jobType" class="form-label required">工作类型</label>
                <select 
                  class="form-select" 
                  id="jobType" 
                  v-model="formData.jobType"
                  :class="{ 'is-invalid': errors.jobType }"
                  required
                >
                  <option value="">请选择工作类型</option>
                  <option value="internship">实习</option>
                  <option value="part_time">兼职</option>
                  <option value="full_time">全职</option>
                </select>
                <div class="invalid-feedback" v-if="errors.jobType">{{ errors.jobType }}</div>
              </div>
            </div>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="companyName" class="form-label required">公司名称</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="companyName" 
                  placeholder="请输入公司全称" 
                  v-model="formData.companyName"
                  :class="{ 'is-invalid': errors.companyName }"
                  required
                >
                <div class="invalid-feedback" v-if="errors.companyName">{{ errors.companyName }}</div>
              </div>
              <div class="col-md-6 mb-3">
                <label for="industry" class="form-label">行业领域</label>
                <select class="form-select" id="industry" v-model="formData.industry">
                  <option value="">请选择行业</option>
                  <option value="internet">互联网/IT</option>
                  <option value="finance">金融/银行</option>
                  <option value="education">教育/培训</option>
                  <option value="media">媒体/广告</option>
                  <option value="manufacturing">制造业</option>
                  <option value="service">服务业</option>
                  <option value="other">其他</option>
                </select>
              </div>
            </div>
            
            <div class="mb-3">
              <label for="companyDescription" class="form-label">公司介绍</label>
              <textarea 
                class="form-control" 
                id="companyDescription" 
                rows="3" 
                placeholder="请简要介绍公司背景、规模、业务范围等" 
                v-model="formData.companyDescription"
              ></textarea>
            </div>
            
            <div class="mb-3">
              <label for="workLocation" class="form-label required">工作地点</label>
              <input 
                type="text" 
                class="form-control" 
                id="workLocation" 
                placeholder="例如：北京市海淀区" 
                v-model="formData.workLocation"
                :class="{ 'is-invalid': errors.workLocation }"
                required
              >
              <div class="invalid-feedback" v-if="errors.workLocation">{{ errors.workLocation }}</div>
            </div>
            
            <div class="mb-3">
              <label for="workAddressDetail" class="form-label">详细地址</label>
              <input 
                type="text" 
                class="form-control" 
                id="workAddressDetail" 
                placeholder="例如：中关村大街XX号科技大厦A座10层" 
                v-model="formData.workAddressDetail"
              >
            </div>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="workMode" class="form-label">工作方式</label>
                <select class="form-select" id="workMode" v-model="formData.workMode">
                  <option value="on_site">现场办公</option>
                  <option value="remote">远程办公</option>
                  <option value="hybrid">混合办公</option>
                </select>
              </div>
              <div class="col-md-6 mb-3">
                <label for="recruitmentCount" class="form-label">招聘人数</label>
                <input 
                  type="number" 
                  class="form-control" 
                  id="recruitmentCount" 
                  min="1" 
                  v-model.number="formData.recruitmentCount"
                >
              </div>
            </div>
          </div>
          
          <div class="navigation-buttons">
            <div></div> <!-- 空div用于占位 -->
            <button type="button" class="btn btn-publish next-step" @click="nextStep">下一步</button>
          </div>
        </div>
        
        <!-- 第二步：职位详情 -->
        <div class="form-section" :class="{ active: currentStep === 2 }" id="step2">
          <div class="publish-card">
            <h3 class="section-title">职位详情</h3>
            
            <div class="mb-3">
              <label for="jobDescription" class="form-label required">职位描述</label>
              <textarea 
                class="form-control" 
                id="jobDescription" 
                rows="4" 
                placeholder="请详细描述职位信息、工作内容等" 
                v-model="formData.jobDescription"
                :class="{ 'is-invalid': errors.jobDescription }"
                required
              ></textarea>
              <div class="invalid-feedback" v-if="errors.jobDescription">{{ errors.jobDescription }}</div>
            </div>
            
            <div class="mb-3">
              <label for="jobResponsibilities" class="form-label">工作职责</label>
              <div class="responsibility-item" v-for="(item, index) in jobResponsibilities" :key="index">
                <div class="input-group mb-2">
                  <span class="input-group-text">{{ index + 1 }}.</span>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="jobResponsibilities[index]"
                    placeholder="请输入工作职责"
                  >
                  <button class="btn btn-outline-danger" type="button" @click="removeResponsibility(index)">
                    <i class="bi bi-x"></i>
                  </button>
                </div>
              </div>
              <button type="button" class="btn btn-outline-primary btn-sm" @click="addResponsibility">
                <i class="bi bi-plus"></i> 添加工作职责
              </button>
            </div>
            
            <div class="mb-3">
              <label for="jobRequirements" class="form-label required">职位要求</label>
              <div class="requirement-item" v-for="(item, index) in jobRequirements" :key="index">
                <div class="input-group mb-2">
                  <span class="input-group-text">{{ index + 1 }}.</span>
                  <input 
                    type="text" 
                    class="form-control" 
                    v-model="jobRequirements[index]"
                    placeholder="请输入职位要求"
                    :class="{ 'is-invalid': errors.jobRequirements && index === 0 }"
                  >
                  <button class="btn btn-outline-danger" type="button" @click="removeRequirement(index)">
                    <i class="bi bi-x"></i>
                  </button>
                </div>
              </div>
              <button type="button" class="btn btn-outline-primary btn-sm" @click="addRequirement">
                <i class="bi bi-plus"></i> 添加职位要求
              </button>
              <div class="invalid-feedback" v-if="errors.jobRequirements">{{ errors.jobRequirements }}</div>
            </div>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="educationRequirement" class="form-label">学历要求</label>
                <select class="form-select" id="educationRequirement" v-model="formData.educationRequirement">
                  <option value="none">不限</option>
                  <option value="high_school">高中及以上</option>
                  <option value="college">大专及以上</option>
                  <option value="bachelor">本科及以上</option>
                  <option value="master">硕士及以上</option>
                  <option value="doctor">博士及以上</option>
                </select>
              </div>
              <div class="col-md-6 mb-3">
                <label for="graduationYear" class="form-label">毕业年份要求</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="graduationYear" 
                  placeholder="例如：2026届" 
                  v-model="formData.graduationYear"
                >
              </div>
            </div>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="workDuration" class="form-label">工作时长</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="workDuration" 
                  placeholder="例如：3-6个月" 
                  v-model="formData.workDuration"
                >
              </div>
              <div class="col-md-6 mb-3">
                <label for="workSchedule" class="form-label">工作时间安排</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="workSchedule" 
                  placeholder="例如：周一至周五 9:00-18:00" 
                  v-model="formData.workSchedule"
                >
              </div>
            </div>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="weeklyDays" class="form-label">每周工作天数</label>
                <input 
                  type="number" 
                  class="form-control" 
                  id="weeklyDays" 
                  min="1" 
                  max="7" 
                  placeholder="例如：5" 
                  v-model.number="formData.weeklyDays"
                >
              </div>
              <div class="col-md-6 mb-3">
                <label for="startDate" class="form-label">工作开始日期</label>
                <input 
                  type="date" 
                  class="form-control" 
                  id="startDate" 
                  v-model="formData.startDate"
                >
              </div>
            </div>
            
            <div class="mb-3">
              <label class="form-label">薪资待遇</label>
              <div class="salary-inputs">
                <select class="form-select" id="salaryType" style="max-width: 150px;" v-model="formData.salaryType">
                  <option value="monthly">月薪</option>
                  <option value="hourly">时薪</option>
                  <option value="daily">日薪</option>
                  <option value="negotiable">面议</option>
                  <option value="unpaid">无薪</option>
                </select>
                <input 
                  type="number" 
                  class="form-control" 
                  id="minSalary" 
                  placeholder="最低薪资" 
                  min="0" 
                  step="0.01"
                  v-model.number="formData.minSalary"
                >
                <span class="salary-separator">-</span>
                <input 
                  type="number" 
                  class="form-control" 
                  id="maxSalary" 
                  placeholder="最高薪资" 
                  min="0" 
                  step="0.01"
                  v-model.number="formData.maxSalary"
                >
                <span>元</span>
              </div>
              <div class="form-tips">如果薪资面议或无薪，可不填写具体金额</div>
            </div>
            
            <div class="mb-3">
              <label for="salaryRemark" class="form-label">薪资备注</label>
              <input 
                type="text" 
                class="form-control" 
                id="salaryRemark" 
                placeholder="例如：根据能力面议、包含餐补等" 
                v-model="formData.salaryRemark"
              >
            </div>
            
            <div class="mb-3">
              <label for="benefits" class="form-label">福利待遇</label>
              <textarea 
                class="form-control" 
                id="benefits" 
                rows="2" 
                placeholder="例如：餐补、交通补贴、实习证明等" 
                v-model="formData.benefits"
              ></textarea>
            </div>
            
            <div class="mb-3">
              <label for="deadline" class="form-label">申请截止日期</label>
              <input 
                type="date" 
                class="form-control" 
                id="deadline" 
                v-model="formData.deadline"
              >
            </div>
            
            <div class="mb-3">
              <label for="urgencyLevel" class="form-label">紧急程度</label>
              <select class="form-select" id="urgencyLevel" v-model="formData.urgencyLevel">
                <option value="low">低</option>
                <option value="medium" selected>中</option>
                <option value="high">高</option>
              </select>
            </div>
            
            <div class="mb-3">
              <label class="form-label">职位标签</label>
              <div class="tag-input-container" id="tagContainer">
                <span v-for="(tag, index) in tags" :key="index" class="tag">
                  {{ tag }}
                  <span class="tag-remove" @click="removeTag(index)">×</span>
                </span>
                <input 
                  type="text" 
                  class="tag-input" 
                  id="tagInput" 
                  placeholder="输入标签后按回车添加，多个标签可用逗号或空格分隔"
                  v-model="newTag"
                  @keydown.enter.prevent="addTag"
                  @blur="handleTagInputBlur"
                >
              </div>
              <div class="form-tips">添加相关标签有助于求职者更快找到您的职位，例如：Java、实习、计算机专业等</div>
            </div>
          </div>
          
          <div class="navigation-buttons">
            <button type="button" class="btn btn-secondary prev-step" @click="prevStep">上一步</button>
            <button type="button" class="btn btn-publish next-step" @click="nextStep">下一步</button>
          </div>
        </div>
        
        <!-- 第三步：联系方式 -->
        <div class="form-section" :class="{ active: currentStep === 3 }" id="step3">
          <div class="publish-card">
            <h3 class="section-title">联系方式</h3>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="contactPerson" class="form-label required">联系人</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="contactPerson" 
                  placeholder="请输入联系人姓名" 
                  v-model="formData.contactPerson"
                  :class="{ 'is-invalid': errors.contactPerson }"
                  required
                >
                <div class="invalid-feedback" v-if="errors.contactPerson">{{ errors.contactPerson }}</div>
              </div>
              <div class="col-md-6 mb-3">
                <label for="contactDepartment" class="form-label">联系部门</label>
                <input 
                  type="text" 
                  class="form-control" 
                  id="contactDepartment" 
                  placeholder="例如：人力资源部" 
                  v-model="formData.contactDepartment"
                >
              </div>
            </div>
            
            <div class="row">
              <div class="col-md-6 mb-3">
                <label for="contactPhone" class="form-label required">联系电话</label>
                <input 
                  type="tel" 
                  class="form-control" 
                  id="contactPhone" 
                  placeholder="请输入联系电话" 
                  v-model="formData.contactPhone"
                  :class="{ 'is-invalid': errors.contactPhone }"
                  required
                >
                <div class="invalid-feedback" v-if="errors.contactPhone">{{ errors.contactPhone }}</div>
              </div>
              <div class="col-md-6 mb-3">
                <label for="contactEmail" class="form-label required">联系邮箱</label>
                <input 
                  type="email" 
                  class="form-control" 
                  id="contactEmail" 
                  placeholder="请输入联系邮箱" 
                  v-model="formData.contactEmail"
                  :class="{ 'is-invalid': errors.contactEmail }"
                  required
                >
                <div class="invalid-feedback" v-if="errors.contactEmail">{{ errors.contactEmail }}</div>
              </div>
            </div>
            
            <div class="mb-3">
              <label for="applicationMethod" class="form-label">申请方式</label>
              <textarea 
                class="form-control" 
                id="applicationMethod" 
                rows="3" 
                placeholder="请说明申请流程，例如：发送简历至邮箱、在线填写申请表等" 
                v-model="formData.applicationMethod"
              ></textarea>
            </div>
            
            <div class="mb-3">
              <label class="form-label">公司Logo/图片</label>
              <div 
                class="image-upload-area" 
                id="imageUploadArea"
                @click="triggerFileInput"
                @dragover.prevent="handleDragOver"
                @dragleave.prevent="handleDragLeave"
                @drop.prevent="handleDrop"
              >
                <div class="upload-icon">
                  <i class="fas fa-cloud-upload-alt"></i>
                </div>
                <p>点击或拖拽图片到此区域上传</p>
                <p class="form-tips">支持 JPG、PNG 格式，大小不超过 5MB</p>
                <img 
                  v-if="imagePreview" 
                  :src="imagePreview" 
                  class="preview-image" 
                  alt="预览图片"
                >
              </div>
              <input 
                type="file" 
                id="imageInput" 
                accept="image/*" 
                style="display: none;"
                @change="handleImageChange"
              >
            </div>
            
            <div class="mb-3 form-check">
              <input 
                type="checkbox" 
                class="form-check-input" 
                id="agreeTerms" 
                v-model="formData.agreeTerms"
                :class="{ 'is-invalid': errors.agreeTerms }"
                required
              >
              <label class="form-check-label" for="agreeTerms">
                我已阅读并同意 <a href="#" @click.prevent="showServiceProtocolModal">《用户服务协议》</a> 和 <a href="#" @click.prevent="showProtocolModal">《信息发布规范》</a>
              </label>
              <div class="invalid-feedback" v-if="errors.agreeTerms">{{ errors.agreeTerms }}</div>
            </div>
          </div>
          
          <div class="navigation-buttons">
            <button type="button" class="btn btn-secondary prev-step" @click="prevStep">上一步</button>
            <button type="submit" class="btn btn-publish">发布信息</button>
          </div>
        </div>
      </form>
      
      <!-- 成功提示模态框 -->
      <div class="modal fade" :class="{ 'show': showSuccessModal }" tabindex="-1" :aria-hidden="!showSuccessModal" :style="{ display: showSuccessModal ? 'block' : 'none' }" v-if="showSuccessModal">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content success-modal">
            <div class="modal-body text-center">
              <div class="success-icon">
                <i class="bi bi-check-circle-fill"></i>
              </div>
              <h4 class="mt-3">发布成功!</h4>
              <p>您的职位信息已成功发布</p>
            </div>
            <div class="modal-footer justify-content-center">
              <button type="button" class="btn btn-success" @click="showSuccessModal = false">确定</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 失败提示模态框 -->
      <div class="modal fade" :class="{ 'show': showErrorModal && !showSuccessModal }" tabindex="-1" :aria-hidden="!showErrorModal || showSuccessModal" :style="{ display: (showErrorModal && !showSuccessModal) ? 'block' : 'none' }" v-if="showErrorModal && !showSuccessModal">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content error-modal">
            <div class="modal-body text-center">
              <div class="error-icon">
                <i class="bi bi-exclamation-circle-fill"></i>
              </div>
              <h4 class="mt-3">发布失败!</h4>
              <p>{{ errorMessage }}</p>
            </div>
            <div class="modal-footer justify-content-center">
              <button type="button" class="btn btn-danger" @click="showErrorModal = false">确定</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 信息发布规范模态框 -->
      <div class="modal fade" :class="{ 'show': showProtocolModalFlag }" tabindex="-1" :aria-hidden="!showProtocolModalFlag" :style="{ display: showProtocolModalFlag ? 'block' : 'none' }" v-if="showProtocolModalFlag">
        <div class="modal-dialog modal-dialog-centered modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">信息发布规范</h5>
              <button type="button" class="btn-close" @click="showProtocolModalFlag = false"></button>
            </div>
            <div class="modal-body">
              <InformationReleaseProtocol />
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary" @click="showProtocolModalFlag = false">关闭</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 用户服务协议模态框 -->
      <div class="modal fade" :class="{ 'show': showServiceProtocolModalFlag }" tabindex="-1" :aria-hidden="!showServiceProtocolModalFlag" :style="{ display: showServiceProtocolModalFlag ? 'block' : 'none' }" v-if="showServiceProtocolModalFlag">
        <div class="modal-dialog modal-dialog-centered modal-lg">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title">用户服务协议</h5>
              <button type="button" class="btn-close" @click="showServiceProtocolModalFlag = false"></button>
            </div>
            <div class="modal-body">
              <UserServiceProtocol />
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-primary" @click="showServiceProtocolModalFlag = false">关闭</button>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 模态框背景遮罩 -->
      <div v-if="(showSuccessModal || showErrorModal || showProtocolModalFlag || showServiceProtocolModalFlag) && !((showSuccessModal && showErrorModal) || (showSuccessModal && showProtocolModalFlag) || (showErrorModal && showProtocolModalFlag) || (showSuccessModal && showServiceProtocolModalFlag) || (showErrorModal && showServiceProtocolModalFlag) || (showProtocolModalFlag && showServiceProtocolModalFlag))" class="modal-backdrop fade show"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from 'vue'
import { createInternshipJob } from '@/api/Internship.js'
import InformationReleaseProtocol from '@/protocol/InformationReleaseProtcol.vue'
import UserServiceProtocol from '@/protocol/UserServiceProtocol.vue'

// 当前步骤
const currentStep = ref(1)

// 表单数据
const formData = reactive({
  // 基本信息
  jobTitle: '',              // 职位名称 (job_title)
  jobType: '',               // 工作类型 (job_type): internship/part_time/full_time
  companyName: '',           // 公司名称 (company_name)
  industry: '',              // 行业领域 (industry)
  companyDescription: '',    // 公司介绍 (company_description)
  workLocation: '',          // 工作地点 (work_location)
  workAddressDetail: '',     // 详细地址 (work_address_detail)
  workMode: 'on_site',       // 工作方式 (work_mode): on_site/remote/hybrid
  recruitmentCount: 1,       // 招聘人数 (recruitment_count)
  
  // 工作详情
  jobDescription: '',        // 职位描述 (job_description)
  benefits: '',              // 福利待遇 (benefits)
  
  // 工作时间与安排
  workDuration: '',          // 工作时长 (work_duration)
  workSchedule: '',          // 工作时间安排 (work_schedule)
  weeklyDays: 5,             // 每周工作天数 (weekly_days)
  startDate: '',             // 工作开始日期 (start_date)
  
  // 薪资待遇
  salaryType: 'monthly',     // 薪资类型 (salary_type): hourly/daily/monthly/negotiable/unpaid
  minSalary: null,           // 最低薪资 (min_salary)
  maxSalary: null,           // 最高薪资 (max_salary)
  salaryRemark: '',          // 薪资备注 (salary_remark)
  
  // 招聘要求
  educationRequirement: 'bachelor',  // 学历要求 (education_requirement): high_school/college/bachelor/master/doctor/none
  graduationYear: '',                // 毕业年份要求 (graduation_year)
  deadline: '',                      // 申请截止日期 (deadline)
  urgencyLevel: 'medium',            // 紧急程度 (urgency_level): low/medium/high
  
  // 联系信息
  contactPerson: '',         // 联系人 (contact_person)
  contactDepartment: '',     // 联系部门 (contact_department)
  contactPhone: '',          // 联系电话 (contact_phone)
  contactEmail: '',          // 联系邮箱 (contact_email)
  applicationMethod: '',     // 申请方式 (application_method)
  
  // 标签
  jobTags: [],               // 职位标签 (job_tags)
  
  // 其他
  agreeTerms: false          // 同意条款
})

// 工作职责和职位要求作为独立的响应式数组
const jobResponsibilities = ref([''])  // 初始化时有一个空项
const jobRequirements = ref([''])     // 初始化时有一个空项

// 添加工作职责
const addResponsibility = () => {
  jobResponsibilities.value.push('')
}

// 删除工作职责
const removeResponsibility = (index) => {
  if (jobResponsibilities.value.length > 1) {
    jobResponsibilities.value.splice(index, 1)
  }
}

// 添加职位要求
const addRequirement = () => {
  jobRequirements.value.push('')
}

// 删除职位要求
const removeRequirement = (index) => {
  if (jobRequirements.value.length > 1) {
    jobRequirements.value.splice(index, 1)
  }
}

// 标签相关
const tags = ref([])
const newTag = ref('')

// 图片上传相关
const imagePreview = ref('')
const imageFile = ref(null)

// 错误信息
const errors = reactive({})

// 模态框显示控制
const showSuccessModal = ref(false)
const showErrorModal = ref(false)
const showProtocolModalFlag = ref(false)
const showServiceProtocolModalFlag = ref(false)
const errorMessage = ref('发布过程中出现错误，请稍后重试')

// 显示信息发布规范模态框
const showProtocolModal = () => {
  showProtocolModalFlag.value = true
}

// 显示用户服务协议模态框
const showServiceProtocolModal = () => {
  showServiceProtocolModalFlag.value = true
}

// 添加标签
const addTag = () => {
  if (newTag.value.trim()) {
    const newTags = newTag.value.split(/[,，\s]+/).filter(tag => tag.trim() !== '');
    
    // 创建普通数组而不是响应式数组
    const updatedTags = [...tags.value];
    
    // 添加标签
    newTags.forEach(tag => {
      const trimmedTag = tag.trim();
      if (trimmedTag && !updatedTags.includes(trimmedTag)) {
        updatedTags.push(trimmedTag);
      }
    });
    
    // 更新响应式引用
    tags.value = [...updatedTags];
    
    // 同步更新 formData.jobTags - 使用普通数组
    formData.jobTags = [...updatedTags];
    
    newTag.value = '';
    
    console.log('Tags updated:', updatedTags);
  }
}

// 为标签输入框添加失去焦点时也添加标签的功能
const handleTagInputBlur = () => {
  if (newTag.value.trim()) {
    addTag();
  }
}

// 删除标签
const removeTag = (index) => {
  // 创建普通数组
  const updatedTags = [...tags.value];
  updatedTags.splice(index, 1);
  
  // 更新响应式引用
  tags.value = [...updatedTags];
  
  // 同步更新 formData.jobTags - 使用普通数组
  formData.jobTags = [...updatedTags];
  
  console.log('Tags after removal:', updatedTags);
}

// 触发文件选择
const triggerFileInput = () => {
  document.getElementById('imageInput').click()
}

// 处理拖拽事件
const handleDragOver = () => {
  const uploadArea = document.getElementById('imageUploadArea')
  uploadArea.style.borderColor = '#3498db'
  uploadArea.style.background = '#f8f9fa'
}

// 处理拖拽离开事件
const handleDragLeave = () => {
  const uploadArea = document.getElementById('imageUploadArea')
  uploadArea.style.borderColor = '#ddd'
  uploadArea.style.background = 'white'
}

// 处理文件放下事件
const handleDrop = (e) => {
  const uploadArea = document.getElementById('imageUploadArea')
  uploadArea.style.borderColor = '#ddd'
  uploadArea.style.background = 'white'
  
  if (e.dataTransfer.files.length) {
    handleImageFile(e.dataTransfer.files[0])
  }
}

// 处理图片文件
const handleImageFile = (file) => {
  // 简单的文件类型和大小验证
  const validImageTypes = ['image/jpeg', 'image/png', 'image/webp'];
  if (!validImageTypes.includes(file.type)) {
    alert('请上传 JPG、PNG 或 WEBP 格式的图片！');
    return
  }
  
  if (file.size > 5 * 1024 * 1024) {
    alert('图片大小不能超过5MB！')
    return
  }
  
  imageFile.value = file
  
  const reader = new FileReader()
  reader.onload = (e) => {
    imagePreview.value = e.target.result
  }
  reader.readAsDataURL(file)
}

// 处理图片选择变化
const handleImageChange = (e) => {
  if (e.target.files.length) {
    handleImageFile(e.target.files[0])
  }
}

// 步骤导航
const nextStep = () => {
  if (validateStep(currentStep.value)) {
    currentStep.value++
  }
}

const prevStep = () => {
  currentStep.value--
}

// 表单验证
const validateStep = (step) => {
  // 清除之前的错误
  Object.keys(errors).forEach(key => {
    delete errors[key]
  })
  
  let isValid = true
  
  // 根据步骤验证不同字段
  if (step === 1) {
    if (!formData.jobTitle.trim()) {
      errors.jobTitle = '请输入职位名称'
      isValid = false
    }
    if (!formData.jobType) {
      errors.jobType = '请选择工作类型'
      isValid = false
    }
    if (!formData.companyName.trim()) {
      errors.companyName = '请输入公司名称'
      isValid = false
    }
    if (!formData.workLocation.trim()) {
      errors.workLocation = '请输入工作地点'
      isValid = false
    }
  } else if (step === 2) {
    if (!formData.jobDescription.trim()) {
      errors.jobDescription = '请输入职位描述'
      isValid = false
    }
    
    // 检查职位要求是否都填写了
    const hasRequirement = jobRequirements.value.some(req => req.trim() !== '')
    if (!hasRequirement) {
      errors.jobRequirements = '请至少添加一个职位要求'
      isValid = false
    }
  } else if (step === 3) {
    if (!formData.contactPerson.trim()) {
      errors.contactPerson = '请输入联系人'
      isValid = false
    }
    if (!formData.contactPhone.trim()) {
      errors.contactPhone = '请输入联系电话'
      isValid = false
    }
    if (!formData.contactEmail.trim()) {
      errors.contactEmail = '请输入联系邮箱'
      isValid = false
    }
    if (!formData.agreeTerms) {
      errors.agreeTerms = '请同意用户服务协议'
      isValid = false
    }
  }
  
  return isValid
}

// 表单提交
const submitForm = async () => {
  if (validateStep(3)) {
    try {
      // 确保标签数据正确提取
      const actualTags = Array.isArray(tags.value) ? 
        [...tags.value] : 
        (Array.from?.(tags.value) || []);
      
      const actualFormTags = Array.isArray(formData.jobTags) ? 
        [...formData.jobTags] : 
        (Array.from?.(formData.jobTags) || []);
      
      // 使用实际的标签数组，优先使用 tags.value
      const finalJobTags = actualTags.length > 0 ? actualTags : actualFormTags;
      
      // 准备提交数据，使用后端能接收的字段名
      const submitData = {
        // 基本信息
        jobTitle: formData.jobTitle,
        jobType: formData.jobType,
        companyName: formData.companyName,
        industry: formData.industry,
        companyDescription: formData.companyDescription,
        workLocation: formData.workLocation,
        workAddressDetail: formData.workAddressDetail,
        workMode: formData.workMode,
        recruitmentCount: formData.recruitmentCount,
        
        // 工作详情
        jobDescription: formData.jobDescription,
        jobResponsibilities: JSON.stringify(jobResponsibilities.value.filter(item => item.trim() !== '')),
        jobRequirements: JSON.stringify(jobRequirements.value.filter(item => item.trim() !== '')),
        benefits: formData.benefits,
        
        // 工作时间与安排
        workDuration: formData.workDuration,
        workSchedule: formData.workSchedule,
        weeklyDays: formData.weeklyDays,
        startDate: formData.startDate,
        
        // 薪资待遇
        salaryType: formData.salaryType,
        minSalary: formData.minSalary,
        maxSalary: formData.maxSalary,
        salaryRemark: formData.salaryRemark,
        
        // 招聘要求
        educationRequirement: formData.educationRequirement,
        graduationYear: formData.graduationYear,
        deadline: formData.deadline,
        urgencyLevel: formData.urgencyLevel,
        
        // 联系信息
        contactPerson: formData.contactPerson,
        contactDepartment: formData.contactDepartment,
        contactPhone: formData.contactPhone,
        contactEmail: formData.contactEmail,
        applicationMethod: formData.applicationMethod,
        
        // 标签 - 保持为数组格式，让API层处理转换为JSON字符串
        jobTags: finalJobTags
      };
      
      // 调试信息
      console.log('Final jobTags:', finalJobTags);
      console.log('Final jobTags length:', finalJobTags.length);
      console.log('Final jobTags type:', typeof finalJobTags);
      console.log('Is final jobTags array:', Array.isArray(finalJobTags));
      
      // 调用API提交数据
      const response = await createInternshipJob(submitData, imageFile.value);
      
      // 调试信息，帮助了解响应结构
      console.log('API Response:', response);
      
      // 确保隐藏任何可能已显示的模态框
      showErrorModal.value = false;
      showSuccessModal.value = false;
      
      // 检查响应，根据后端返回的code字段判断成功与否
      // 由于request.js中已经处理了响应拦截，直接检查response.data即可
      const isSuccess = response.code === 0;
      console.log('Is success:', isSuccess);
      
      if (isSuccess) {
        // 使用 nextTick 确保 DOM 更新后再显示新模态框
        nextTick(() => {
          // 显示成功模态框
          showSuccessModal.value = true;
          
          // 1.5秒后自动关闭
          setTimeout(() => {
            showSuccessModal.value = false;
            // 可以在这里添加跳转到其他页面的逻辑
            // router.push('/some-page');
          }, 1500);
        });
      } else {
        // 使用 nextTick 确保 DOM 更新后再显示新模态框
        nextTick(() => {
          // 显示失败模态框并设置错误信息
          if (response.data) {
            errorMessage.value = response.data.msg || response.data.message || '发布失败，请稍后重试';
          } else {
            errorMessage.value = response.msg || response.message || '发布失败，请稍后重试';
          }
          showErrorModal.value = true;
          
          // 1.5秒后自动关闭
          setTimeout(() => {
            showErrorModal.value = false;
          }, 1500);
        });
      }
      
    } catch (error) {
      console.error('提交失败:', error);
      // 显示失败模态框
      errorMessage.value = '网络错误，请检查连接后重试';
      showErrorModal.value = true;
    }
  }
}
</script>

<style scoped>
:root {
  --primary-color: #3498db;
  --secondary-color: #2980b9;
  --accent-color: #e74c3c;
  --light-color: #f8f9fa;
  --dark-color: #343a40;
  --success-color: #2ecc71;
}

body {
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  background-color: #f5f7fa;
  color: #333;
  line-height: 1.6;
}

.publish-header {
  background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
  color: white;
  padding: 2rem 0;
  border-radius: 0 0 20px 20px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.1);
  margin-bottom: 2rem;
}

.publish-container {
  max-width: 900px;
  margin: 0 auto;
}

.publish-card {
  background: white;
  border-radius: 15px;
  box-shadow: 0 5px 15px rgba(0,0,0,0.05);
  padding: 2rem;
  margin-bottom: 2rem;
}

.section-title {
  font-weight: 600;
  color: var(--primary-color);
  border-left: 4px solid var(--primary-color);
  padding-left: 10px;
  margin: 1.5rem 0 1rem;
}

.form-label {
  font-weight: 600;
  color: #555;
  margin-bottom: 0.5rem;
}

.required::after {
  content: " *";
  color: var(--accent-color);
}

.form-control, .form-select {
  border-radius: 8px;
  padding: 10px 15px;
  border: 1px solid #ddd;
  transition: all 0.3s;
}

.form-control:focus, .form-select:focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 0.2rem rgba(52, 152, 219, 0.25);
}

.btn-publish {
  background: var(--primary-color);
  color: white;
  font-weight: 600;
  padding: 12px 30px;
  border-radius: 8px;
  border: none;
  transition: all 0.3s;
  font-size: 1.1rem;
}

.btn-publish:hover {
  background: var(--secondary-color);
  transform: translateY(-2px);
}

.btn-secondary {
  background: var(--light-color);
  color: var(--dark-color);
  font-weight: 500;
  padding: 10px 20px;
  border-radius: 8px;
  border: 1px solid #ddd;
  transition: all 0.3s;
}

.btn-secondary:hover {
  background: #e9ecef;
}

.tag-input-container {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 10px;
  min-height: 42px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.tag {
  display: inline-flex;
  align-items: center;
  background: #e1f0fa;
  color: var(--primary-color);
  padding: 5px 12px;
  border-radius: 20px;
  font-size: 0.85rem;
}

.tag-remove {
  margin-left: 5px;
  cursor: pointer;
  font-weight: bold;
}

.tag-input {
  border: none;
  outline: none;
  flex-grow: 1;
  min-width: 100px;
}

.salary-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.salary-separator {
  color: #666;
}

.image-upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.image-upload-area:hover {
  border-color: var(--primary-color);
  background: #f8f9fa;
}

.upload-icon {
  font-size: 3rem;
  color: #ccc;
  margin-bottom: 1rem;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 8px;
  margin-top: 1rem;
}

.form-tips {
  font-size: 0.85rem;
  color: #666;
  margin-top: 0.5rem;
}

.step-indicator {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;
  position: relative;
}

.step-indicator::before {
  content: '';
  position: absolute;
  top: 15px;
  left: 0;
  right: 0;
  height: 2px;
  background: #e9ecef;
  z-index: 1;
}

.step {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2;
}

.step-number {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: #e9ecef;
  color: #666;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-bottom: 5px;
}

.step.active .step-number {
  background: var(--primary-color);
  color: white;
}

.step-label {
  font-size: 0.85rem;
  color: #666;
}

.step.active .step-label {
  color: var(--primary-color);
  font-weight: 600;
}

.form-section {
  display: none;
}

.form-section.active {
  display: block;
}

.navigation-buttons {
  display: flex;
  justify-content: space-between;
  margin-top: 2rem;
}

@media (max-width: 768px) {
  .publish-card {
    padding: 1.5rem;
  }
  
  .salary-inputs {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .salary-separator {
    display: none;
  }
}

.responsibility-item, .requirement-item {
  margin-bottom: 8px;
}

.responsibility-item .input-group-text,
.requirement-item .input-group-text {
  width: 40px;
  justify-content: center;
}

/* 成功和失败模态框样式 */
.success-modal, .error-modal {
  border: none;
  border-radius: 15px;
  box-shadow: 0 5px 20px rgba(0,0,0,0.15);
}

.success-modal .modal-body, 
.error-modal .modal-body {
  padding: 2rem;
}

.success-icon {
  font-size: 3rem;
  color: #28a745;
}

.error-icon {
  font-size: 3rem;
  color: #dc3545;
}

.modal-body h4 {
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.modal-body p {
  color: #666;
  margin-bottom: 0;
}

.btn-success {
  background: #28a745;
  border: none;
  padding: 8px 25px;
}

.btn-danger {
  background: #dc3545;
  border: none;
  padding: 8px 25px;
}
</style>